package com.ita.ftp;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class FtpClient{
	
	private String host;
	private int port;
	public final static String DOWNLOAD_PATH = "./downloads";
	
	public FtpClient(String host, int port) {
		super();
		this.host = host;
		this.port = port;
	}
	
	public void connect() throws UnknownHostException, IOException {
		Socket socket = new Socket(host, port);
		BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		BufferedReader readConsole = new BufferedReader(new InputStreamReader(System.in));
		OutputStream outputStream = socket.getOutputStream();
		OutputStream fileOutPutStream = null;
		BufferedOutputStream bufferedOutputStream = null;
		String consoleString = "";
		String line = null;
		while (true) {
			while (!(line = reader.readLine()).equals(" ")) {
				if(consoleString.startsWith("download")){
					if (line.equals("-- Download file!")) {
						System.out.println(line);
						fileOutPutStream = new FileOutputStream(DOWNLOAD_PATH + "/" +consoleString.split(" ")[1]);
						bufferedOutputStream = new BufferedOutputStream(fileOutPutStream);
					}
					else if(line.startsWith("-- ")){
						System.out.println(line);
					}
					else {
						System.out.println("-----------------------------------------------------------------------------------------------" + line.getBytes().length);
						System.out.println(line);
						if(line.contains("end")){
							String tmp = line.substring(0, line.length() - 3);
							System.out.println(tmp);
							bufferedOutputStream.write(tmp.getBytes());	
							bufferedOutputStream.close();
						}else {
							bufferedOutputStream.write(line.getBytes());
						}
					}
				}else {					
					System.out.println(line);
				}
			};
			consoleString = readConsole.readLine();
			if(consoleString.equals("bye")) {
				outputStream.write(("bye\n").getBytes());
				break;
			}
			outputStream.write(( consoleString + "\n").getBytes());
		}
		
		reader.close();
		outputStream.close();
		socket.close();
	}
}
